package com.jsoft.images;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;

import clioptions.CliOptions;
import clioptions.exceptions.parsing.ParsingException;


public class Main {
	static boolean noGui = true;
	static String inputFileName, outputFileName;
	
	public static void main(String[] args) {
		CliOptions cliOptions = new CliOptions("hg", 
				Arrays.asList("help", "gui"));
		
		try {
			cliOptions.parse(args);
			if (cliOptions.isOptionSet("h") || cliOptions.isOptionSet("help")) {
				usage();
				return;
			}
			
			if (cliOptions.isOptionSet("g") || cliOptions.isOptionSet("gui")) {
				noGui = false;
			}
			
			String rargs[] = cliOptions.getRemaningArgs();
			if (rargs.length > 2) {
				System.err.println("Extra arguments");
				usage();
				return;
			}
			if (rargs.length > 1) {
				outputFileName = rargs[1];
			}

			if (rargs.length > 0) {
				inputFileName = rargs[0];
			}
			
			if (outputFileName == null && !noGui) {
				System.err.println("Not enough arguments");
				usage();
				return;
				
			}
		} catch (ParsingException e) {
			System.err.println(e.getMessage());
			usage();
			return;
		}

		if (noGui) {
			processCLI();
		}

	}

	public static void processCLI() {
		BufferedImage img = null;
		try {
		    img = ImageIO.read(new File(inputFileName));
		    
		    String outputSuffix = null;
		    int i = outputFileName.lastIndexOf('.');
		    if (i > 0) {
		        outputSuffix = outputFileName.substring(i+1);
		    }
		    
		    if (outputSuffix == null) {
		    	System.err.println("No suffix in " + outputFileName);
		    	return;
		    }
		    
		    Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersBySuffix(outputSuffix);
		    if (!imageWriters.hasNext()) {
		    	System.err.println("No writer for suffix " + outputSuffix);
		    }
		    ImageWriter imageWriter = imageWriters.next();
		    String[] mimeTypes = imageWriter.getOriginatingProvider().getMIMETypes();
		    
		    i = mimeTypes[0].lastIndexOf('/');
		    String formatName = mimeTypes[0].substring(i + 1);
		    if (!ImageIO.write(img, formatName, new File(outputFileName))) {
		    	System.out.println("Failed to find writer for " + mimeTypes[0]);
		    }
		} catch (IOException e) {
			System.err.println(e + ": " + inputFileName);
		}
		
		

	}
	public static void usage() {
		System.err.println("Images [<options>] <input file> <output file>");
		System.err.println("-h|--help print this message and exit");
		System.err.println("-g|--gui Run in gui mode");
	}
}
